﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Graphics.PackedVector;
using Microsoft.Xna.Framework;
using System.IO;
using Block.Audio;

namespace Block
{
    static class Loader
    {
        public static Texture2D LoadTexture(GraphicsDevice graphicsDevice,string path)
        {
            StreamReader rd = new StreamReader(path);
            Texture2D temp=Texture2D.FromStream(graphicsDevice, rd.BaseStream);
            PreMultiplyAlphas(temp);
            return temp;
        }
        public static AudioStream LoadAudioStream(String FileName,bool isLoop=false)
        {
            return new AudioStream(FileName,isLoop);
        }
        private static void PreMultiplyAlphas(Texture2D ret)
        {
            Byte4[] data = new Byte4[ret.Width * ret.Height];
            ret.GetData<Byte4>(data);
            for (int i = 0; i < data.Length; i++)
            {
                Vector4 vec = data[i].ToVector4();
                float alpha = vec.W / 255.0f;
                int a = (int)(vec.W);
                int r = (int)(alpha * vec.X);
                int g = (int)(alpha * vec.Y);
                int b = (int)(alpha * vec.Z);
                uint packed = (uint)(
                    (a << 24) +
                    (b << 16) +
                    (g << 8) +
                    r
                    );

                data[i].PackedValue = packed;
            }
            ret.SetData<Byte4>(data);
        }
    }
}
